import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import weixinShare from '../../lib/weixinShare';
import { addErrorListener } from '../../lib/handleError';

import makeTime from './makeTime'

import AJAX from '../../lib/ajax';

import weui from 'weui.js'
import { isBoolean } from 'util';

import Agreement from './agreement';

require('../../lib/rem');
require('../../styles/common.less');
require('./SendExpress.less');
require('../../styles/iconfont/iconfont.css');

class SendExpress extends Component {
  constructor(props) {
    super(props)

    this.SenderInfo = [];
    this.ReceiverInfo = [];

    if (sessionStorage.getItem('senderInfo')) { // 获取收件人信息
      this.SenderInfo = sessionStorage.getItem('senderInfo').replace(/\s*/g, "").split('#')

      this.SenderInfo[1] = `${this.SenderInfo[1].substring(0, 3)} ${this.SenderInfo[1].substring(3, 7)} ${this.SenderInfo[1].substring(7, 11)}`;

      let i = 2
      while (i <= 4) {
        this.SenderInfo[i] = JSON.parse(this.SenderInfo[i])
        i++
      }
    }

    if (sessionStorage.getItem('receiverInfo')) { // 获取收件人信息
      this.ReceiverInfo = sessionStorage.getItem('receiverInfo').replace(/\s*/g, "").split('#')

      this.ReceiverInfo[1] = `${this.ReceiverInfo[1].substring(0, 3)} ${this.ReceiverInfo[1].substring(3, 7)} ${this.ReceiverInfo[1].substring(7, 11)}`;

      let i = 2
      while (i <= 5) {
        this.ReceiverInfo[i] = JSON.parse(this.ReceiverInfo[i])
        i++
      }
    }
    
    this.state = {
      isEjectTips: false, // 是否显示保价说明
      isEjectGoods: false, // 是否显示类型重量选择
      isAgreement: false, // 是否显示电子面单服务条款
      isReady: false,     //是否可以加载页面
      placeSuccess: false, // 是否完成下单
      isAgreeClause: true, //是否同意条款
      SenderInfo: {
        name: this.SenderInfo[0] || '寄件人信息',
        phone: this.SenderInfo[1] || '',
        address: this.SenderInfo.length >= 1 ?
          `${this.SenderInfo[2][1]} ${this.SenderInfo[3][1]} ${this.SenderInfo[4][1]} ${this.SenderInfo[5]}`
          :
          '点击填写寄件人信息'
      }, // 寄件人信息
      ReceiverInfo: { // 收件人信息
        name: this.ReceiverInfo[0] || '收件人信息',
        
        phone: this.ReceiverInfo[1] || '',

        address: this.ReceiverInfo.length >= 1 ?
          `${this.ReceiverInfo[2][1]} ${this.ReceiverInfo[3][1]} ${this.ReceiverInfo[4][1]} ${this.ReceiverInfo[5][1]}`
          :
          '点击填写收件人信息'
      },
      makeTime: makeTime[0].label, // 预约时间
      startTime: makeTime[0].startTime,
      endTime: makeTime[0].endTime,
      goodsType: '日用品',
      goodsWeight: 1, // 默认重量
      totalFee: '-', // 预估价格
      open_id: '', // 用户open_id
    };
  }

  componentWillMount() {
    addErrorListener()()
    weixinShare.hideAll()
  }

  componentDidMount() {
    AJAX.appendBaiduAnalysis()

    this.valuation();

    setTimeout(() => {
      this.setState({
        isReady: true, //是否可以加载页面
      })
    }, 10)
  }

  handleTime() {
    weui.picker(makeTime,
    {
      className: 'custom-classname',
      container: 'body',
      defaultValue: [0],
      
      onConfirm: (result) => {
        this.setState({
          makeTime: result[0].label,
          startTime: result[0].startTime,
          endTime: result[0].endTime
        })
      },
      title: '预约上门时间'
    }
    )
  }

  handleRoute (type) {
    switch (type) {
      case 1:
        window.location.href="./SenderInfo";
        return;
      case 2:
        window.location.href="./ReceiverInfo";
        return;
    }
  }

  checkSubmit () {
    if (this.state.SenderInfo.name == '寄件人信息' || !this.state.SenderInfo.name) {
      return [0, '请先完善寄件人信息'];
    } else if (this.state.ReceiverInfo.name == '收件人信息' || !this.state.ReceiverInfo.name) {
      return [0, '请先完善收件人信息'];
    } else if (!this.state.isAgreeClause) {
      return [0, '请点击同意《快件运单契约条款》'];
    } else {
      return [1, '验证成功']
    }
  }

  handleSubmit () { // 提交订单
    const checkResult = this.checkSubmit();
    switch (checkResult[0]) {
      case 0:
        weui.topTips(checkResult[1]);
        break;
      case 1:
        const isMobile = /^[1][3|4|5|6|7|8|9]\d{9}$/;
        this.SenderInfo[1] = this.SenderInfo[1].replace(/\s*/g, "");
        this.ReceiverInfo[1] = this.ReceiverInfo[1].replace(/\s*/g, "");

        const params = {
          totalWeight: this.state.goodsWeight,
          cargoName: this.state.goodsType,
          insuranceValue: this.refs.price.value || 0,
          sendStartTime: this.state.startTime,
          sendEndTime: this.state.endTime,
          sender: {
            name: this.SenderInfo[0],
            phone: isMobile.test(this.SenderInfo[1]) ? null : this.SenderInfo[1],
            mobile: isMobile.test(this.SenderInfo[1]) ? this.SenderInfo[1] : null,
            province: this.SenderInfo[2][1],
            provinceCode: this.SenderInfo[2][0],
            city: this.SenderInfo[3][1],
            cityCode: this.SenderInfo[3][0],
            county: this.SenderInfo[4][1],
            countyCode: this.SenderInfo[4][0],
            address: this.SenderInfo[5],
          },

          receiver: {
            name: this.ReceiverInfo[0],
            phone: isMobile.test(this.ReceiverInfo[1]) ? null : this.ReceiverInfo[1],
            mobile: isMobile.test(this.ReceiverInfo[1]) ? this.ReceiverInfo[1] : null,
            province: this.ReceiverInfo[2][1],
            provinceCode: this.ReceiverInfo[2][0],
            city: this.ReceiverInfo[3][1],
            cityCode: this.ReceiverInfo[3][0],
            county: this.ReceiverInfo[4][1],
            countyCode: this.ReceiverInfo[4][0],
            address: this.ReceiverInfo[5][1],
          },
          
          logisId: this.ReceiverInfo[5][0],
          openId: this.state.open_id,
        }
        AJAX.operPost("addOrder", params, (res) => {
          if (res.data.code == 0) {
            this.setState({
              placeSuccess: true
            })
          }
        })
    }
  }

  handleCloseWindow () {
    WeixinJSBridge.call('closeWindow');
  }

  handleChangeType (type) {
    this.setState({
      isEjectGoods: type,
    })
  }

  handleClause (e, agreed) { // 是否同意条款
    agreed = agreed || !this.state.isAgreeClause

    this.setState({
      isAgreeClause: agreed,
      isAgreement: false
    })
  }

  handleChangeTips () {
    this.setState({
      isEjectTips: !this.state.isEjectTips
    })
  }

  changeWeight (type) {
    let i = 0;
    switch (type) {
      case 1:
        if (this.state.goodsWeight <= 1) {
          weui.topTips('重量不能低于1kg');
          return;
        }
        i--;
        break;
      case 2:
        i++;
        break;
    }
    
    this.setState({
      goodsWeight: this.state.goodsWeight + i
    }, () => {
      this.valuation()
    })
  }

  selectType (index, text) {
    const type_box = this.refs.type_box.children;
    const thisCard = type_box[index];

    for (let i = 0; i < type_box.length; i++) {
      type_box[i].classList.value = ''
    }

    thisCard.classList.value = 'active';
    this.setState({
      goodsType: text
    })
  }

  valuation() { // 估价
    const senderSure = this.SenderInfo.length > 4 && this.SenderInfo[2][1] && this.SenderInfo[3][1] && this.SenderInfo[4][1];
    const receiptSure = this.ReceiverInfo.length > 4 && this.ReceiverInfo[2][1] && this.ReceiverInfo[3][1] && this.ReceiverInfo[4][1];

    if (senderSure && receiptSure) {
      let params = {
        originalsStreet: `${this.ReceiverInfo[2][1]}-${this.ReceiverInfo[3][1]}-${this.ReceiverInfo[4][1]}`,
        originalsAddress: `${this.SenderInfo[2][1]}-${this.SenderInfo[3][1]}-${this.SenderInfo[4][1]}`,
        sendDateTime: this.state.startTime,
        totalVolume: '0.001',
        totalWeight: this.state.goodsWeight
      }

      AJAX.fetchGet("priceEvaluation", params, (data) => {
        this.setState({
          totalFee: data.totalfee
        })
      })
    }
  }

  handleBlur () {
    window.scroll(0, 0);
  }

  ejectTips () {
    return (
      <div className="ejectTips-bg">
        <div className="ejectTips">
          <h2 className="tipsTitle">保价说明</h2>
          <ul className="tipsList">
            <li>
              <span>1.</span>
              预估费用仅供参考，具体以开单收取为准
            </li>
            <li>
              <span>2.</span>
              物流普通保价费费率为0.6%，其中小 票货物最低收费12元，大票货物最低收 费24元，（大票定义为单票货物重量大于500kg或者体积大于2.5立方）
            </li>
            <li>
              <span>3.</span>
              快递普通保价（保价声明价值小于等 于2万，费率为4‰，高保价率为5‰）
            </li>
          </ul>
          <button type="button" className="handleSubmit" onClick={this.handleChangeTips.bind(this)}>我知道了</button>
        </div>
      </div>
    )
  }

  handleAgreement (e) {
    e.stopPropagation()
    
    this.setState({
      isAgreement: true
    })
  }

  placeOrderSuccess () {
    return (
      <div className="ejectTips-bg">
        <div className="ejectTips ejectPlace">
          <h2 className="tipsTitle">下单成功</h2>
          <p className="tipsContent">尊敬的用户<br/>您的寄件订单已成功下单，请等候快递员联系取件。</p>
          <button type="button" className="handleSubmit" onClick={this.handleCloseWindow.bind(this)}>知道了</button>
        </div>
      </div>
    )
  }

  ejectGoods () {
    return (
      <div>
        <div className={this.state.isEjectGoods ? 'ejectGoods ejectGoodsShow change' : 'ejectGoods change'}>
          <div className="ejectGoods_weight">
            <label className="weight_title">重量预估</label>
            <div className="weight_box">
              <a className="icon iconfont iconIcon_reduce" onClick={this.changeWeight.bind(this, 1)}></a>
              <span>{this.state.goodsWeight}kg</span>
              <a className="icon iconfont iconIcon_add" onClick={this.changeWeight.bind(this, 2)}></a>
            </div>
          </div>
          
          <div className="ejectGoods_type">
            <h4 className="type_title">物品类型</h4>
            <dl className="type_box" ref="type_box">
              <dt data-index="0" onClick={() => this.selectType(0, '文件')}>文件</dt>
              <dt data-index="1" onClick={() => this.selectType(1, '数码产品')}>数码产品</dt>
              <dt data-index="2" onClick={() => this.selectType(2, '日用品')} className="active">日用品</dt>
              <dt data-index="3" onClick={() => this.selectType(3, '衣服')}>衣服</dt>
              <dt data-index="4" onClick={() => this.selectType(4, '食品')}>食品</dt>
              <dt data-index="5" onClick={() => this.selectType(5, '其他')}>其他</dt>
            </dl>
            <button type="button" onClick={this.handleChangeType.bind(this, false)}>确定</button>
          </div>
        </div>

        <div className={
          this.state.isEjectGoods
            ?
            'ejectTips-bg goods_bg goods_bgShow'
            :
            'ejectTips-bg goods_bg'
          }
          onClick={this.handleChangeType.bind(this, false)}
        >
        </div>
      </div>
    )
  }

  render () {
    const ejectTips = this.ejectTips();
    const ejectGoods = this.ejectGoods();
    const placeOrderSuccess = this.placeOrderSuccess();

    return (
      this.state.isReady &&
      <div style={{height: '100vh', backgroundColor: '#f0f0f0', display: 'flex'}}>
        <div className="express">
          <section className="card">
            <ul className="editList">
              <li>
                <div className="icon">
                  <span className="iconSend">寄</span>
                  <em className="iconLine top"></em>
                </div>
                <div className="edit" onClick={this.handleRoute.bind(this, 1)}>
                  <h2>{this.state.SenderInfo.name}<span>{this.state.SenderInfo.phone}</span></h2>
                  <p>{this.state.SenderInfo.address}</p>
                </div>
              </li>

              <li>
                <div className="icon">
                  <span className="iconAddress">收</span>
                  <em className="iconLine bottom"></em>
                </div>
                <div className="edit" onClick={this.handleRoute.bind(this, 2)}>
                  <h2>{this.state.ReceiverInfo.name}<span>{this.state.ReceiverInfo.phone}</span></h2>
                  <p>{this.state.ReceiverInfo.address}</p>
                </div>
              </li>
            </ul>
          </section>

          <section className="card">
            <ul className="power">
              <li className="powerPrice">
                <label>
                  保价服务
                  <i onClick={this.handleChangeTips.bind(this)} className="icon iconfont iconIcon_warning"></i>
                  <em onClick={this.handleChangeTips.bind(this)}>选填建议足额保价</em>
                </label>
                <span>
                  <input type="number" ref="price" onBlur={this.handleBlur.bind(this)} defaultValue="" placeholder="请输入保价"/>
                  <em>元</em>
                </span>
              </li>

              <li className="powerPrice" onClick={this.handleChangeType.bind(this, true)}>
                <label>
                  类型/重量
                </label>
                <span>
                  <strong>{this.state.goodsType}/{this.state.goodsWeight}kg</strong>
                  <i className="icon iconfont iconIcon_right"></i>
                </span>
              </li>

              <li className="powerPrice" onClick={this.handleTime.bind(this)}>
                <label>
                  预约上门时间
                </label>
                <span>
                  <strong>{this.state.makeTime}</strong>
                  <i className="icon iconfont iconIcon_right"></i>
                </span>
              </li>
            </ul>
          </section>

          <div className="clause" onClick={this.handleClause.bind(this)}>
            <i className={
              this.state.isAgreeClause ?
                'agree icon iconfont iconIcon_duigou'
                :
                'icon iconfont iconIcon_duigou'
              }></i>
            我同意
            <span onClick={this.handleAgreement.bind(this)}>《快件运单契约条款》</span>
          </div>
        </div>

        <div className="powerSubmit">
          <div className="powerSubmit-price">
            <h2>费用预估: <span className={this.state.totalFee && this.state.totalFee != '-' && 'feePrice'}>¥{this.state.totalFee}</span></h2>
            <p>实际以快递小哥上门核算为准</p>
          </div>

          <button type="button" onClick={this.handleSubmit.bind(this)}>提交订单</button>
        </div>
        {this.state.isEjectTips && ejectTips}
        {ejectGoods}
        {this.state.placeSuccess && placeOrderSuccess}
        {this.state.isAgreement &&
          <Agreement
            handleClick={this.handleClause.bind(this)}
            isAgreement={this.state.isAgreement}
            clause={this.state.isAgreeClause}
          />
        }
      </div>
    )
  }
}
ReactDOM.render(<SendExpress />, document.getElementById('app'));
if (module.hot) {
  module.hot.accept();
}

